<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-6-8
 * Time: 16:29
 */

namespace app\web\controller;
use app\common\controller\Api;
use app\common\model\Factor;
use app\common\model\Fenorder;
use app\common\model\HandCardType as HandCardTypeM;
use app\common\model\HandCard as HandCardM;
use app\web\controller\Express;
use think\Db;
use think\Exception;

/**
 * 手牌控制器
 * @package app\index\controller
 */
class HandCard extends Auth
{
    public $noNeedLogin = [];

    /**
     *获取优先排钟列表
     * @return array
     */
    public function lists()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $userInfo = $this->userInfo;
            $page = $this->request->post('page');
            $limit = $this->request->post('limit');
            $sql = Db::name('qt_hand_card')
                ->field('id,name,type')
                ->where(['store_id' => $userInfo['store_id']]);
            if(isset($getData['name']) && !empty($getData['name'])){
                $sql->where('name',$getData['name']);
            }
            if(isset($getData['type']) && !empty($getData['type'])){
                $sql->where('type',$getData['type']);
            }
            $data = $sql->order('id desc')->paginate($limit);
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 添加手牌
     */
    public function add(){
        if ($this->request->isPost()) {
            $getData= $this->request->post();
            if(empty($getData['name']) || empty($getData['type'])){
                $this->result('缺少参数', '', 204);
            }
            $getData['created_time'] = time();
            $getData['store_id'] = $this->userInfo['store_id'];
            $insert = Db::name('qt_hand_card')->insert($getData);
            if($insert){
                $this->result('添加成功', '', 200);
            }
            $this->result('添加失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 编辑手牌
     */
    public function save(){
        if ($this->request->isPost()) {
            $getData= $this->request->post();
            if(empty($getData['name']) || empty($getData['type'])){
                $this->result('缺少参数', '', 204);
            }
            $update= Db::name('qt_hand_card')->where('id',$getData['id'])->update($getData);
            if($update !== false){
                $this->result('修改成功', '', 200);
            }
            $this->result('修改失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 编辑手牌
     */
    public function edit(){
        if ($this->request->isPost()) {
            $getData= $this->request->post();
            if(empty($getData['id'])){
                $this->result('缺少参数', '', 204);
            }
            $data= Db::name('qt_hand_card')
                ->field('id,name,type,card_no')
                ->where('id',$getData['id'])->find();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 删除手牌
     */
    public function delete(){
        if ($this->request->isPost()) {
            $getData= $this->request->post();
            if(empty($getData['id'])){
                $this->result('缺少参数', '', 204);
            }
            $data= Db::name('qt_hand_card')->where('id',$getData['id'])->delete();
            $this->result('删除成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 超时费用列表
     */
    public function price_list()
    {
        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $getData = $this->request->post();
            if (empty($getData['page']) || empty($getData['limit'])) {
                $this->result('缺少参数', '', 204);
            }
            $data = Db::name('qt_hand_card_price')
                ->where('store_id', $userInfo['store_id'])
                ->order('id desc')
                ->paginate($getData['limit'])->each(function ($item){
                    $handTypeIds = explode(',',$item['hand_card_type']);
                    $handType = Db::name('qt_hand_card_type')->whereIn('id',$handTypeIds)->column('name');
                    $item['hand_type_name'] = $handType;
                    return $item;
                });
            $this->result('查询成功', $data, 200);
        } else {
            $this->result('无效的请求', '', 204);
        }
    }

    /**
     * 添加超时费用
     */
    public function add_price()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new \app\web\validate\HandCardPrice();
            if (!$validate->scene('add')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $getData['create_time'] = time();
            $getData['store_id'] = $this->userInfo['store_id'];
            $insert = Db::name('qt_hand_card_price')->insert($getData);
            if ($insert) {
                $this->result('添加成功', '', 200);
            }
            $this->result('添加失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 删除超时费用
     */
    public function delete_price()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['id'])) {
                $this->result('缺少参数', '', 204);
            }
            $room_price = Db::name('qt_hand_card_price')->where('id', $getData['id'])->find();
            //结账
            $product_item = Db::name('qt_product_order_item')->where(['business_type'=>'1'])->where('goods_id',$room_price['product_id'])->find();
            if (!empty($product_item)) {
                $this->result('超市费用已经使用不可删除！', '', 204);
            }
            $del = Db::name('qt_hand_card_price')->where('id', $getData['id'])->delete();
            if ($del) {
                $this->result('删除成功', '', 200);
            }
            $this->result('删除失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 保存超时费用
     */
    public function save_price()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new \app\web\validate\HandCardPrice();
            if (!$validate->scene('add')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $del = Db::name('qt_hand_card_price')->where('id', $getData['id'])->update($getData);
            if ($del !== false) {
                $this->result('保存成功', '', 200);
            }
            $this->result('保存失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 过夜费用列表
     */
    public function night_price_list()
    {
        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $getData = $this->request->post();
            if (empty($getData['page']) || empty($getData['limit'])) {
                $this->result('缺少参数', '', 204);
            }
            $sql = Db::name('qt_hand_card_night_price')
                ->where('store_id', $userInfo['store_id']);
            if(!empty($getData['hand_card_type'])){
                $sql->where("FIND_IN_SET(" . $getData['hand_card_type'] . ",hand_card_type)");
            }
            $data =$sql->order('id desc')
                ->paginate($getData['limit'])->each(function ($item){
                    $handTypeIds = explode(',',$item['hand_card_type']);
                    $handType = Db::name('qt_hand_card_type')->whereIn('id',$handTypeIds)->column('name');
                    $item['hand_type_name'] = $handType;
                    return $item;
                });
            $this->result('查询成功', $data, 200);
        } else {
            $this->result('无效的请求', '', 204);
        }
    }


    /**
     * 添加过夜费用
     */
    public function night_add_price()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new \app\web\validate\HandCardNightPrice();
            if (!$validate->scene('add')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $getData['create_time'] = time();
            $getData['store_id'] = $this->userInfo['store_id'];
            $insert = Db::name('qt_hand_card_night_price')->insert($getData);
            if ($insert) {
                $this->result('添加成功', '', 200);
            }
            $this->result('添加失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }



    /**
     * 删除过夜费用
     */
    public function night_delete_price()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['id'])) {
                $this->result('缺少参数', '', 204);
            }
            $room_price = Db::name('qt_hand_card_night_price')->where('id', $getData['id'])->find();
            //结账
            $product_item = Db::name('qt_product_order_item')->where(['business_type'=>'1'])->where('goods_id',$room_price['product_id'])->find();
            if (!empty($product_item)) {
                $this->result('过夜费用已经使用不可删除！', '', 204);
            }
            $del = Db::name('qt_hand_card_night_price')->where('id', $getData['id'])->delete();
            if ($del) {
                $this->result('删除成功', '', 200);
            }
            $this->result('删除失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 保存过夜费用
     */
    public function night_save_price()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new \app\web\validate\HandCardNightPrice();
            if (!$validate->scene('add')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $del = Db::name('qt_hand_card_night_price')->where('id', $getData['id'])->update($getData);
            if ($del !== false) {
                $this->result('保存成功', '', 200);
            }
            $this->result('保存失败', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 合并手牌
     */
    public function combined()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['hand_grant_id']) || !isset($getData['hand_card_id']) || !isset($getData['hand_card_name'])) {
                $this->result('请选择手牌', '', 204);
            }
            //合并房间数据
            $marge = explode(',',$getData['hand_grant_id']);
            if(count($marge) > 1){
                foreach ($marge as $key => $value) {
                    $update = ['marge' => $getData['hand_grant_id']];
                    Db::name('qt_hand_grant')->where('id', $value)->update($update);
                }
                //插入记录
                $log = [
                    'hand_card_id'=>$getData['hand_card_id'],
                    'hand_card_name'=>$getData['hand_card_name'],
                    'hand_grant_id'=>$getData['hand_grant_id'],
                    'store_id'=>$this->userInfo['store_id'],
                    'user_id'=>$this->userInfo['id'],
                    'create_time'=>time(),
                ];
                Db::name('qt_hand_card_marge')->insert($log);
            }
            $this->result('合并手牌成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }



    /**
     * 查询手牌
     */
    public function search()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['hand_card_name'])) {
                $this->result('请添加手牌', '', 204);
            }
            $find = Db::name('qt_hand_card')
                ->field('hc.id as hand_card_id,hc.name as hand_card_name,hc.status,g.id as hand_grant_id')
                ->alias('hc')
                ->leftJoin('qt_hand_grant g','hc.id = g.hand_card_id')
                ->where(['name'=>$getData['hand_card_name']])
                ->find();
            if(empty($find)){
                $this->result('未找到该手牌', '', 204);
            }
            if ($find['status'] != '2'){
                $this->result('手牌未发放', '', 204);
            }
            $this->result('查询成功', $find, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 过夜费用列表
     */
    public function marge_list()
    {
        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $getData = $this->request->post();
            if (empty($getData['page']) || empty($getData['limit'])) {
                $this->result('缺少参数', '', 204);
            }
            $data =Db::name('qt_hand_card_marge')
                ->field('m.*,u.real_name')
                ->alias('m')
                ->leftJoin('qt_users u','u.id = m.user_id')
                ->where('m.store_id', $userInfo['store_id'])
                ->order('m.id desc')
                ->paginate($getData['limit']);
            $this->result('查询成功', $data, 200);
        } else {
            $this->result('无效的请求', '', 204);
        }
    }


    /**
     * 保存合并手牌
     */
    public function save_combined()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['hand_grant_id']) || !isset($getData['hand_card_id']) || !isset($getData['hand_card_name'])) {
                $this->result('请选择手牌', '', 204);
            }
            //合并房间数据
            $marge = explode(',',$getData['hand_grant_id']);
            foreach ($marge as $key => $value) {
                $update = ['marge' => $getData['hand_grant_id']];
                Db::name('qt_hand_grant')->where('id', $value)->update($update);
            }
            $this->result('修改手牌成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 删除合并手牌
     */
    public function delete_combined()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['id'])) {
                $this->result('请选择合并记录ID', '', 204);
            }
            $hand_card_id = Db::name('qt_hand_card_marge')->where(['id'=>$getData['id']])->value('hand_card_id');
            $marge = explode(',',$hand_card_id);
            foreach ($marge as $key => $value) {
                $update = ['marge' => ''];
                Db::name('qt_hand_grant')->where('id', $value)->update($update);
            }
            $this->result('删除手牌成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 手牌首页
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $return = HandCardM::getList($getData,$this->userInfo);
            if($return['code'] != 200){
                $this->result($return['msg'], '', 204);
            }
            $this->result('查询成功', $return['data'], 200);
        } else {
            $this->result('请使用post请求', '', 204);
        }
    }


    /**
     * 手牌分类列表
     */
    public function type_list()
    {
        if ($this->request->isPost()) {
            $data = HandCardTypeM::field('id,name')->select();
            $this->result('查询成功', $data, 200);
        } else {
            $this->result('请使用post请求', '', 204);
        }
    }

    /**
     * 备注
     */
    public function remarks(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(!isset($getData['content']) || empty($getData['content'])){
                $this->result('请填写备注信息', '', 204);
            }
            if(!isset($getData['hand_grant_id']) || empty($getData['hand_grant_id'])){
                $this->result('缺少参数', '', 204);
            }
            $update = Db::name('qt_hand_grant')->where('id',$getData['hand_grant_id'])->update(['content'=>$getData['content']]);
            if($update !== false ){
                $this->result('备注成功', '', 200);
            }
            $this->result('备注失败', '', 204);
        }
        $this->result('无效的请求方式', '', 204);
    }


    /**
     * 取消备注
     */
    public function del_remarks(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(!isset($getData['hand_grant_id']) || empty($getData['hand_grant_id'])){
                $this->result('缺少参数', '', 204);
            }
            $update = Db::name('qt_hand_grant')->where('id',$getData['hand_grant_id'])->update(['content'=>'']);
            if($update !== false ){
                $this->result('取消成功', '', 200);
            }
            $this->result('取消失败', '', 204);
        }
        $this->result('无效的请求方式', '', 204);
    }

    /**
     * 回收手牌
     */
    public function recovery(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(!isset($getData['name']) || empty($getData['name'])){
                $this->result('缺少参数', '', 204);
            }
            if($this->storeInfo['type'] == '1'){
                $this->result('门店模式不正确', '', 204);
            }
            $handCard = Db::name('qt_hand_card')->where('name',$getData['name'])->find();
            if(empty($handCard)){
                $this->result('无效的手牌', '', 204);
            }
            if($handCard['status']  == '3'){
                $this->result('手牌状态有问题', '', 204);
            }
            $update = [
                'status'=>'3',
                'update_time'=>time(),
                'recovery_id'=>$this->userInfo['id']
            ];
            try{
                Db::startTrans();
                //修改订单状态
                Db::name('qt_hand_card')->where(['id'=>$handCard['id']])->update(['status'=>'1']);
                Db::name('qt_hand_grant')->where(['hand_card_id'=>$handCard['id']])->update($update);
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                $this->result('取消失败','',204);
            }
            $this->result('取消成功', '', 200);
        }
        $this->result('无效的请求方式', '', 204);
    }


    /**
     * 未发放的手牌
     */
    public function no_send()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['hand_card_name'])) {
                $this->result('请添加手牌', '', 204);
            }
            $find = Db::name('qt_hand_card')
                ->field('id as hand_card_id,name as hand_card_name')
                ->where(['name'=>$getData['hand_card_name'],'status'=>'1','store_id'=>$this->userInfo['store_id']])
                ->find();
            if(empty($find)){
                $this->result('手牌未发放', $find, 204);
            }else{
                $this->result('查询成功', $find, 200);
            }

        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 已经发放的手牌
     */
    public function send()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['hand_card_name'])) {
                $this->result('请添加手牌', '', 204);
            }
            $find = Db::name('qt_hand_card')
                ->field('hc.id as hand_card_id,hc.name as hand_card_name,hc.status,g.id as hand_grant_id')
                ->alias('hc')
                ->leftJoin('qt_hand_grant g','hc.id = g.hand_card_id')
                ->where(['hc.name'=>$getData['hand_card_name'],'hc.status'=>'2'])
                ->whereIn('g.status',['2','4'])
                ->find();
            if(empty($find)){
                $this->result('无效的手牌，或者手牌未发放', '', 204);
            }else{
                $this->result('查询成功', $find, 200);
            }

        }
        $this->result('无效的请求', '', 204);
    }



    /**
     * 获取手牌配置
     */
    public function getConfig()
    {
        if ($this->request->isPost()) {
            $data = Db::name('qt_hand_card_config')
                ->where(['store_id'=>$this->userInfo['store_id'],'user_id'=>$this->userInfo['id']])
                ->find();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 保存手牌配置
     */
    public function saveConfig()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['id'])){
                $insert = [
                    'store_id'=>$this->userInfo['store_id'],
                    'user_id'=>$this->userInfo['id'],
                    'is_auto_print'=>$getData['is_auto_print'],
                    'time'=>$getData['time'],
                ];
                $save = Db::name('qt_hand_card_config')->insert($insert);
            }else{
                $save = Db::name('qt_hand_card_config')
                    ->where(['id'=>$getData['id']])
                    ->update($getData);
            }
            if($save){
                $this->result('保存成功', '', 200);
            }
            $this->result('保存失败', '', 204);

        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 取消手牌
     */
    public function cancel(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(!isset($getData['hand_grant_id']) || empty($getData['hand_grant_id'])){
                $this->result('缺少参数', '', 204);
            }
            $handGrant = Db::name('qt_hand_grant')->where('id',$getData['hand_grant_id'])->find();
            //添加门票
            $ticket = new \app\common\model\AdmissionTicket();
            $result = $ticket::delAdmissionPrice($handGrant['hand_card_id']);
            if($result['status'] == false){
                $this->result($result['msg'], '', 204);
            }
            //判断是否有未结账的商品和项目
            $projectOrder = Db::name('qt_order_project')
                ->where(['hand_card_id'=>$handGrant['hand_card_id'],'pay_status'=>'0','is_delete'=>'2','is_change'=>'1'])
                ->find();

            $goodsOrder = Db::name('qt_product_order_item')
                ->where(['hand_card_id'=>$handGrant['hand_card_id'],'pay_status'=>'0','status'=>'1'])
                ->find();
            if(!empty($projectOrder) || !empty($goodsOrder)){
                $this->result('手牌未结账', '', 204);
            }
            $handGrant = Db::name('qt_hand_grant')->where('id',$getData['hand_grant_id'])->find();
            $update = Db::name('qt_hand_grant')->where('id',$getData['hand_grant_id'])->update(['status'=>'3']);
            Db::name('qt_hand_card')->where('id',$handGrant['hand_card_id'])->update(['status'=>'1']);
            if($update !== false ){
                $this->result('取消成功', '', 200);
            }
            $this->result('取消失败', '', 204);
        }
        $this->result('无效的请求方式', '', 204);
    }


    /**
     * 发放手牌
     */
    public function grant(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(!isset($getData['name']) || empty($getData['name'])){
                $this->result('缺少参数', '', 204);
            }
            if($this->storeInfo['type'] == '1'){
                $this->result('门店模式不正确', '', 204);
            }
            $handCardNames = explode(',',$getData['name']);
            foreach ($handCardNames as $key=>$value){
                $handCard = Db::name('qt_hand_card')->where('name',$value)->find();
                if(empty($handCard)){
                    $this->result('无效的手牌', '', 204);
                }
                if($handCard['status'] != '1'){
                    $this->result('手牌状态有问题', '', 204);
                }
                if($getData['marge'] == '1'){
                    $handCardIds = Db::name('qt_hand_card')->whereIn('name',$handCardNames)->column('id');
                }
                $money = \app\common\model\HandCard::checkMoney($handCard['id']);
                $insert = [
                    'hand_card_id'=>$handCard['id'],
                    'grant_id'=>$this->userInfo['id'],
                    'store_id'=>$this->userInfo['store_id'],
                    'status'=>'2',
                    'money'=>$money,
                    'create_time'=>time()
                ];
                try{
                    Db::startTrans();
                    //修改订单状态
                    Db::name('qt_hand_card')->where(['id'=>$handCard['id']])->update(['status'=>'2']);
                    $grantID = Db::name('qt_hand_grant')->insertGetId($insert);
                    if($getData['marge'] == '1'){
                        Db::name('qt_hand_grant')->where('id',$grantID)->update(['marge'=>$handCardIds]);
                        //插入记录
                        $log = [
                            'hand_card_id'=>$handCard['id'],
                            'hand_card_name'=>$value,
                            'hand_grant_id'=>$grantID,
                            'store_id'=>$this->userInfo['store_id'],
                            'user_id'=>$this->userInfo['id'],
                            'create_time'=>time(),
                        ];
                        Db::name('qt_hand_card_marge')->insert($log);
                    }
                    //添加门票
                    $ticket = new \app\common\model\AdmissionTicket();
                    $result= $ticket::admissionTicketPrice($handCard['type'],$handCard['id'],$this->userInfo);
                    if($result['status'] == false){
                        $this->result($result['msg'],'',204);
                    }
                    Db::commit();
                }catch (Exception $exception){
                    Db::rollback();
                    $this->result('发放失败','',204);
                }
            }

            $this->result('发放成功', '', 200);
        }
        $this->result('无效的请求方式', '', 204);
    }

    /**
     * 获取当前手牌的合并信息
     */
    public function get_marge(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (!isset($getData['hand_grant_id'])) {
                $this->result('请选择手牌', '', 204);
            }
            $handGrantId = Db::name('qt_hand_grant')->where(['id'=>$getData['hand_grant_id']])->value('marge');
            if(empty($handGrantId)){
                $handCardName[0] = Db::name('qt_hand_grant')
                    ->field('c.name,g.id as hand_grant_id,c.id as hand_card_id')
                    ->alias('g')
                    ->leftJoin('qt_hand_card c','c.id = g.hand_card_id')
                    ->where(['g.id'=>$getData['hand_grant_id']])
                    ->find();
            }else{
                $handGrantId = explode(',',$handGrantId);
                $handCardName = Db::name('qt_hand_card')
                    ->field('c.name,g.id as hand_grant_id,c.id as hand_card_id')
                    ->alias('c')
                    ->leftJoin('qt_hand_grant g','g.hand_card_id = c.id')
                    ->where(['g.status'=>'2'])
                    ->whereIn('g.id',$handGrantId)
                    ->select();
            }
            $this->result('查询成功', $handCardName, 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 转手牌
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function transfer()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (empty($post['old_hand_card_id']) || empty($post['new_hand_card_name']) || empty($post['old_hand_grant_id'])) {
                $this->result('请选择手牌', '', 204);
            }

            $new_hand_card_data = Db::name('qt_hand_card')
                ->where('store_id', $this->userInfo['store_id'])
                ->where('name', $post['new_hand_card_name'])
                ->find();
            if (empty($new_hand_card_data)) $this->result('没有找到手牌'.$post['new_hand_card_name'] .'号','',204);

            //判断新手牌是否发放,如果手牌使用了不能发放
            $new_hand_grant_data = Db::name('qt_hand_grant')
                ->where('store_id', $this->userInfo['store_id'])
                ->where('hand_card_id', $new_hand_card_data['id'])
                ->where('status',2)
                ->find();
            if (!empty($new_hand_grant_data)) $this->result('手牌已经发放','',204);


            $project_order_data = Db::name('qt_order_project')
                ->where('hand_card_id', $post['old_hand_card_id'])
                ->where('is_delete', 2)
                ->where('is_change', 1)
                ->where('pay_status', 0)
                ->select();

            $goods_order_data = Db::name('qt_product_order_item')
                ->where(['hand_card_id' => $post['old_hand_card_id'], 'pay_status' => '0'])
                ->select();

            //检测手牌最大消费金额
            $hand_order_total_money = array_sum(array_column($project_order_data,'price')) + array_sum(array_column($goods_order_data,'goods_price'));
            $checkMoney = \app\common\model\HandCard::checkMaxMoney($new_hand_card_data['id'],$hand_order_total_money);
            if($checkMoney == false){
                $this->result('手牌超出最大消费', '', 204);
            }

            $old_grant_data = Db::name('qt_hand_grant')->where(['id' => $post['old_hand_grant_id']])->order('id desc')->find();

            //更新新房间信息
            Db::startTrans();
            try {

                //更新项目
                foreach ($project_order_data as $key => $value) {

                    Db::name('qt_order_project')
                        ->where(['id' => $value['id']])
                        ->update([
                            'hand_card_id' => $new_hand_card_data['id'],
                            'old_card_id' => $post['old_hand_card_id']
                        ]);
                }

                foreach ($goods_order_data as $key => $value) {
                    Db::name('qt_product_order_item')->where(['id' => $value['id']])
                        ->update([
                            'hand_card_id' => $new_hand_card_data['id'],
                            'old_card_id' => $post['old_hand_card_id']
                        ]);
                }

                //老手牌更改为空闲
                Db::name('qt_hand_card')->where('id', $post['old_hand_card_id'])->update(['status' => '1']);
                //老手牌记录更改为已回收
                Db::name('qt_hand_grant')->where('id', $post['old_hand_grant_id'])->update(['status' => '3']);
                //新手牌改为使用中
                Db::name('qt_hand_card')->where('id', $new_hand_card_data['id'])->update(['status' => '2']);

                //修改记录
                Db::name('qt_hand_grant')->insert([
                    'store_id' => $this->userInfo['store_id'],
                    'hand_card_id' => $new_hand_card_data['id'],
                    'grant_id' => $this->userInfo['id'],
                    'recovery_id' => '',
                    'viper_card_id' => '',
                    'money' => $old_grant_data['money'] ?? 0,
                    'payment_money' => $old_grant_data['payment_money'] ?? 0,
                    'max_money' => 0,
                    'status' => $old_grant_data['status'],
                    'create_time' => time(),
                ]);
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('转手牌失败', '', 204);
            }

            $this->result('转手牌成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 手牌转账
     */
    public function transfer_accounts()
    {
        if ($this->request->isPost()) {

            $post = $this->request->post();
            if (empty($post['old_hand_card_id']) || empty($post['new_hand_card_name']) || empty($post['old_hand_grant_id'])) {
                $this->result('请选择手牌', '', 204);
            }

            $new_hand_card_data = Db::name('qt_hand_card')
                ->where('store_id', $this->userInfo['store_id'])
                ->where('name', $post['new_hand_card_name'])
                ->find();
            if (empty($new_hand_card_data)) $this->result('没有找到手牌'.$post['new_hand_card_name'] .'号','',204);

            //判断新手牌是否发放,如果手牌使用了不能发放
            $new_hand_grant_data = Db::name('qt_hand_grant')
                ->where('store_id', $this->userInfo['store_id'])
                ->where('hand_card_id', $new_hand_card_data['id'])
                ->where('status',2)
                ->find();
            if (empty($new_hand_grant_data)) $this->result('手牌未发放','',204);


            $project_order_data = Db::name('qt_order_project')
                ->where('hand_card_id', $post['old_hand_card_id'])
                ->where('is_delete', 2)
                ->where('is_change', 1)
                ->where('pay_status', 0)
                ->select();

            $goods_order_data = Db::name('qt_product_order_item')
                ->where(['hand_card_id' => $post['old_hand_card_id'], 'pay_status' => '0'])
                ->select();

            $old_grant_money = Db::name('qt_hand_grant')->where(['id' => $post['old_hand_grant_id']])->order('id desc')->value('money');
            $new_grant_money = Db::name('qt_hand_grant')->where(['id' => $new_hand_card_data['id']])->order('id desc')->value('money');

            //更新新房间信息
            Db::startTrans();
            try {
                //更新订单房间
                //更新项目房间
                foreach ($project_order_data as $key => $value) {
                    Db::name('qt_order_project')->where(['id' => $value['id']])
                        ->update([
                            'hand_card_id' => $new_hand_card_data['id'],
                            'old_card_id'=>$post['old_hand_card_id']
                        ]);

                }
                //更新产品房间
                foreach ($goods_order_data as $key => $value) {
                    Db::name('qt_product_order_item')->where(['id' => $value['id']])
                        ->update([
                            'hand_card_id' => $new_hand_card_data['id'],
                            'old_card_id'=>$post['old_hand_card_id']
                        ]);
                }
                //新手牌增加金额
                Db::name('qt_hand_grant')->where('id', $new_hand_grant_data['id'])->update(['money' => $old_grant_money + $new_grant_money]);
                //老手牌金额为0
                Db::name('qt_hand_grant')->where('id', $post['old_hand_grant_id'])->update(['money' => 0]);

                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('转账失败', '', 204);
            }

            $this->result('转账成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 设置最大金额
     */
    public function setMaxMoney(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['hand_grant_id'])) {
                $this->result('请选择手牌', '', 204);
            }
            $update = Db::name('qt_hand_grant')->where(['id'=>$getData['hand_grant_id']])->update(['max_money'=>$getData['max_money']]);
            if($update !== false){
                $this->result('设置成功', '', 200);
            }
            $this->result('设置失败', '', 204);
        }
    }

    /**
     * 停牌
     */
    public function stop(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['hand_grant_id'])) {
                $this->result('请选择手牌', '', 204);
            }
            $handCardID = Db::name('qt_hand_grant')->where(['id'=>$getData['hand_grant_id']])->value('hand_card_id');
            try{
                Db::startTrans();
                //更新发放记录
                Db::name('qt_hand_grant')->where(['id'=>$getData['hand_grant_id']])->update(['status'=>'4']);
                //更新手牌状态
                Db::name('qt_hand_card')->where(['id'=>$handCardID])->update(['status'=>'4']);
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                $this->result('操作失败','',204);
            }
            $this->result('操作成功', '', 200);

        }
    }

    /**
     * 取消停牌
     */
    public function restart(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['hand_grant_id'])) {
                $this->result('请选择手牌', '', 204);
            }
            $handCardID = Db::name('qt_hand_grant')->where(['id'=>$getData['hand_grant_id']])->value('hand_card_id');
            try{
                Db::startTrans();
                //更新发放记录
                Db::name('qt_hand_grant')->where(['id'=>$getData['hand_grant_id']])->update(['status'=>'2']);
                //更新手牌状态
                Db::name('qt_hand_card')->where(['id'=>$handCardID])->update(['status'=>'2']);
                Db::commit();
            }catch (Exception $exception) {
                Db::rollback();
                $this->result('操作失败', '', 204);
            }
            $this->result('操作成功', '', 200);

        }
    }

    /**
     * 手牌发放记录
     */
    public function grantLog()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $totalSql = Db::name('qt_hand_grant')
                ->field('count(grant.id) as number,type.name as hand_card_type,grant.create_time')
                ->alias('grant')
                ->leftJoin('qt_hand_card card','card.id = grant.hand_card_id')
                ->leftJoin('qt_hand_card_type type','card.type = type.id')
                ->where(['grant.store_id'=>$this->userInfo['store_id']]);
            $sql = Db::name('qt_hand_grant')
                ->field('grant.*,type.name as hand_card_type,u.real_name as grant_name,card.name as hand_card_name')
                ->alias('grant')
                ->leftJoin('qt_hand_card card','card.id = grant.hand_card_id')
                ->leftJoin('qt_hand_card_type type','card.type = type.id')
                ->leftJoin('qt_users u','u.id = grant.grant_id')
                ->where(['grant.store_id'=>$this->userInfo['store_id']]);
            //手牌号筛选
            if(isset($getData['hand_card_name']) && !empty($getData['hand_card_name'])){
                $sql->where('card.name',$getData['hand_card_name']);
                $totalSql->where('card.name',$getData['hand_card_name']);
            }
            //状态筛选
            if(isset($getData['status']) && !empty($getData['status'])){
                $sql->where('grant.status',$getData['status']);
                $totalSql->where('grant.status',$getData['status']);
            }
            //类型
            if(isset($getData['type']) && !empty($getData['type'])){
                $sql->where('card.type',$getData['type']);
                $totalSql->where('card.type',$getData['type']);
            }
            //时间筛选
            if(isset($getData['start_time']) && !empty($getData['start_time'])){
                $sql->whereBetweenTime('grant.create_time',strtotime($getData['start_time']),strtotime($getData['end_time']));
                $totalSql->whereBetweenTime('grant.create_time',strtotime($getData['start_time']),strtotime($getData['end_time']));
            }
            $logData = $sql->paginate($getData['limit'])->each(function ($item){
                $item['recovery_name'] = Db::name('qt_users')->where(['id'=>$item['recovery_id']])->value('real_name');
                $item['cancel_name'] = Db::name('qt_users')->where(['id'=>$item['cancel_id']])->value('real_name');
                $checkOutData = Db::name('qt_check_out')->where(['id'=>$item['check_out_id']])->find();
                $item['check_out_order_no'] = $checkOutData['order_no'];
                $item['check_out_cashier_time'] = $checkOutData['cashier_time'];
                return $item;
            });
            $totalData = $totalSql->group('card.type')->select();
            $result['list'] = $logData;
            $result['detail'] = $totalData;
            $this->result('查询成功', $result, 200);
        }
    }


}
